<template>
  <a-spin class="table-gl-con" style="margin-top: 10px" :loading="submitLoading">
    <TableWrap style="flex: 1" @refresh="getTableList">
      <template #headerLeft>
        <a-space>
          <p>共计 {{ total }} 条</p>
          <a-button class="gray-outline" size="medium" @click="changeStatus('ENABLED')">启用</a-button>
          <a-button class="gray-outline" size="medium" @click="changeStatus('PAUSED')">暂停</a-button>
          <a-button class="gray-outline" size="medium" @click="changeStatus('ARCHIVED')">归档</a-button>
          <!-- 暂时只支持SP活动 -->
          <a-button type="primary" size="medium" @click="openCreatePage()" v-if="advertStore.currentCampaign && advertStore.currentCampaign.adType === 'SPONSORED_PRODUCTS'">新增广告组</a-button>
          <a-button class="gray-outline" size="medium" @click="openEditBid">调整竞价</a-button>
        </a-space>
      </template>
      <template #tableBody>
        <a-table
          class="table-singe-line"
          ref="tableRef"
          row-key="id"
          :loading="tableLoading"
          @selection-change="selectColumn"
          :row-selection="rowSelection"
          :bordered="false"
          :data="tableList"
          :scroll="{
            x: 1690,
            y: '100%',
          }"
          size="mini"
          @sorter-change="sorterChange"
          :pagination="false"
        >
          <template #columns>
            <a-table-column :width="80" title="有效" fixed="left">
              <template #cell="{ record }">
                <a-popconfirm v-if="record.state != 'ARCHIVED'" :content="`确定是否${record.state === 'PAUSED' ? '开启' : '暂停'}广告组`" @ok="changeState(record.state, record)" type="warning">
                  <a-switch v-model="record.state" size="medium" checked-value="ENABLED" unchecked-value="PAUSED" :beforeChange="handleChangeIntercept">
                    <template #checked> 开 </template>
                    <template #unchecked> 关 </template>
                  </a-switch>
                </a-popconfirm>
                <a-switch v-else v-model="record.state" disabled checked-value="ENABLED" unchecked-value="ARCHIVED" />
              </template>
            </a-table-column>
            <a-table-column :width="160" title="广告组" fixed="left">
              <template #cell="{ record }">
                <div class="flex-c">
                  <p @click="toDetail(record)" :class="record.state == 'ARCHIVED' ? 'gray cursor' : 'highlight cursor'">{{ record.adGroupName }}</p>
                  <a-popconfirm v-model:popup-visible="record.isPopup" @popup-visible-change="popupChange($event, record.adGroupName)" @ok="updateSingle(record, 'adGroupName', 'adGroupName')">
                    <template #content>
                      <p class="popconfirm-title">广告组名称</p>
                      <a-textarea v-model="editVal" style="width: 260px" placeholder="请输入广告组名称" allow-clear />
                    </template>
                    <a-tooltip content="编辑" trigger="hover" :mini="true" placement="top">
                      <icon-edit :class="record.isPopup ? 'popup-edit-icon' : 'popup-edit-icon popup-edit-icon-hover'" />
                    </a-tooltip>
                  </a-popconfirm>
                  <CopyText style="margin-left: 4px" :class="record.isPopup ? 'popup-edit-icon' : 'popup-edit-icon popup-edit-icon-hover'" :val="record.adGroupName" />
                </div>
              </template>
            </a-table-column>
            <a-table-column :width="60" title="趋势图" fixed="left">
              <template #cell="{ record }">
                <i @click="openAdGroupDetail(record)" class="icon icon-tubiao-zhexiantu highlight cursor"></i>
              </template>
            </a-table-column>
            <a-table-column :width="70" title="状态" fixed="left">
              <template #cell="{ record }">
                <p :class="$extract(statusMap[record.state], 'color')">{{ $extract(statusMap[record.state], 'name') }}</p>
              </template>
            </a-table-column>
            <a-table-column :width="120" title="活动名称" fixed="left">
              <template #cell="{ record }">
                <TextLimit>{{ record.campaignName }}</TextLimit>
              </template>
            </a-table-column>
            <a-table-column :width="80" title="竞价">
              <template #cell="{ record }">
                <div class="flex-c">
                  <p>
                    <span>{{ getCurrencySymbol(record.marketplaceId) }}</span>
                    <span>{{ record.defaultBid }}</span>
                  </p>
                  <a-popconfirm v-model:popup-visible="record.isPopup1" @popup-visible-change="popupChange($event, record.defaultBid)" @ok="updateSingle(record, 'bid', 'defaultBid')">
                    <template #content>
                      <p class="popconfirm-title">竞价</p>
                      <span style="margin-right: 5px">{{ getCurrencySymbol(record.marketplaceId) }}</span>
                      <a-input-number v-model="editVal" style="width: 260px" placeholder="" allow-clear />
                    </template>
                    <icon-edit :class="record.isPopup1 ? 'popup-edit-icon' : 'popup-edit-icon popup-edit-icon-hover'" />
                  </a-popconfirm>
                </div>
              </template>
            </a-table-column>
            <a-table-column :width="85" :sortable="sortable" align="right" data-index="impressions">
              <template #title>
                <a-popover content="广告曝光次数">
                  <p>
                    <span>曝光量</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.impressions || record.impressions === 0">{{ record.impressions }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="85" align="right" :sortable="sortable" data-index="clicks">
              <template #title>
                <a-popover content="广告点击次数">
                  <p>
                    <span>点击量</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.clicks || record.clicks === 0">{{ record.clicks }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="80" title="CTR" align="right" :sortable="sortable" data-index="ctr">
              <template #title>
                <a-popover content="广告点击转化率=点击量/曝光量">
                  <p>
                    <span>CTR</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.ctr || record.ctr === 0">{{ Number(record.ctr).toFixed(2) }}%</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="85" title="花费" align="right" :sortable="sortable" data-index="cost">
              <template #title>
                <a-popover content="亚马逊广告花费">
                  <p>
                    <span>花费</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.cost || record.cost === 0">${{ Number(record.cost).toFixed(2) }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="80" title="CPC" align="right" :sortable="sortable" data-index="cpc">
              <template #title>
                <a-popover content="单次点击成本，CPC=广告花费/点击量">
                  <p>
                    <span>CPC</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.cpc || record.cpc === 0">${{ Number(record.cpc).toFixed(2) }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="80" title="CVR" align="right" :sortable="sortable" data-index="cvr">
              <template #title>
                <a-popover content="广告转化率，CVR=广告订单量/点击量*100%">
                  <p>
                    <span>CVR</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.cvr || record.cvr === 0">{{ Number(record.cvr).toFixed(2) }}%</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="80" title="CPA" align="right" :sortable="sortable" data-index="cpa">
              <template #title>
                <a-popover content="单笔订单平均广告花费，CPA=广告花费/广告订单量">
                  <p>
                    <span>CPA</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.cpa || record.cpa === 0">${{ Number(record.cpa).toFixed(2) }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="85" title="总单量" align="right" :sortable="sortable" data-index="purchasesOrder">
              <template #title>
                <a-popover content="广告带来的订单及关联订单数量">
                  <p>
                    <span>总单量</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.purchasesOrder || record.purchasesOrder === 0">{{ record.purchasesOrder }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="95" title="商品销量" align="right" :sortable="sortable" data-index="purchasesSale">
              <template #title>
                <a-popover content="广告商品销量">
                  <p>
                    <span>商品销量</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.purchasesSale || record.purchasesSale === 0">{{ record.purchasesSale }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="90" title="销售额" align="right" :sortable="sortable" data-index="saleAmount">
              <template #title>
                <a-popover content="广告带来的销售额及关联销售额">
                  <p>
                    <span>销售额</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.saleAmount || record.saleAmount === 0">${{ Number(record.saleAmount).toFixed(2) }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="85" title="ACOS" align="right" :sortable="sortable" data-index="acos">
              <template #title>
                <a-popover content="投入产出比，ACOS=广告花费/广告销售额*100%">
                  <p>
                    <span>ACOS</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.acos || record.acos === 0">{{ Number(record.acos).toFixed(2) }}%</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="85" title="ROAS" align="right" :sortable="sortable" data-index="roas">
              <template #title>
                <a-popover content="支出回报，ROAS=广告销售额/广告花费">
                  <p>
                    <span>ROAS</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.roas || record.roas === 0">{{ Number(record.roas).toFixed(2) }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column title="操作" fixed="right">
              <template #cell="{ record }">
                <a-button type="text" @click="toDetail(record)">详情</a-button>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </template>
    </TableWrap>
    <div class="pagination-footer">
      <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 300]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
    </div>
  </a-spin>
  <!-- 广告组详情 -->
  <CampaignDetail showType="adGroup" v-if="showAdGroupDetail" :defaultSearchVal="searchParams" :currentData="currentData" :isShow="showAdGroupDetail" @closed="showAdGroupDetail = false" />
  <!-- 调整竞价 -->
  <EditBidDialog v-if="showEditDialog" type="adGroup" :list="selectRows" :isShow="showEditDialog" @closed="showEditDialog = false" @success="getTableList" />
</template>
<script lang="ts" setup>
  import { ref, reactive } from 'vue'
  import { adGroupList, updateAdGroup } from '@/api/advert'
  import CampaignDetail from './campaignDetail.vue'
  import EditBidDialog from './editBidDialog.vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import useAdvertStore from '@/store/modules/advert'
  import { AdStatusHandle } from '../../types'
  import { useRouter } from 'vue-router'
  import { marketPlaceList, currencySymbol } from '@/utils/globalData'
  const props = defineProps({
    searchParams: {
      type: Object,
      default: () => {},
    },
  })
  const emit = defineEmits(['update', 'updateNode'])
  const searchVal = ref<any>({
    pageSize: 20,
    pageNum: 1,
  })
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any
  const sortable = reactive({
    sortDirections: ['descend', 'ascend'],
    sorter: true,
  }) as any
  const total = ref(0)
  const tableLoading = ref(false)
  const tableList = ref<Array<any>>([])
  const selectIds = ref([])
  const tableListMap = ref({})
  const editVal = ref<any>()
  const showEditDialog = ref(false)
  const showAdGroupDetail = ref(false)
  const advertStore = useAdvertStore()
  const submitLoading = ref(false)
  const statusMap = {
    ENABLED: { name: '投放中', color: 'success' },
    PAUSED: { name: '已暂停', color: 'normal' },
    ARCHIVED: { name: '已归档', color: 'gray' },
  }
  const showUserDialog = ref(false)
  const currentData = ref<any>({})
  const selectRows = ref<any>([])
  const router = useRouter()
  const tableRef = ref()

  const selectColumn = (val: any) => {
    selectIds.value = val
  }
  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getTableList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableList()
  }
  function getTableListByVal() {
    searchVal.value.pageNum = 1
    getTableList()
  }
  // 进入广告活动详情
  function toDetail(row: any) {
    advertStore.changeGroup({
      adGroupId: row.adGroupId,
      adGroupName: row.adGroupName,
    })
    advertStore.changeCurrentLevel('adGroup')
    router.push('/advert/campaign/campaignDetail')
    emit('updateNode')
  }
  // 获取组合列表数据
  async function getTableList() {
    tableLoading.value = true
    const res: any = await adGroupList({
      ...props.searchParams,
      ...searchVal.value,
    })
    tableLoading.value = false
    tableRef.value.selectAll(false)
    tableList.value = res?.data?.data || []
    total.value = res?.data?.total || 0
    tableListMap.value = {}
    tableList.value.forEach((el) => {
      el.id = el.shopId + el.campaignId + el.adGroupId
      tableListMap.value[el.id] = el
    })
  }
  // 显示货币符号
  function getCurrencySymbol(marketplaceId: string) {
    let currency = marketPlaceList[marketplaceId]?.currency
    return currencySymbol[currency]
  }
  // 进入编辑页面
  function openCreatePage() {
    advertStore.changeDarftInfo({})
    router.push('/advert/campaign/createSpAdGroup')
  }
  // 排序
  function sorterChange(dataIndex: string, direction: string) {
    if (!direction) {
      searchVal.value.orderItems = null
    } else {
      searchVal.value.orderItems = [
        {
          asc: direction == 'ascend' ? true : false,
          column: dataIndex,
        },
      ]
    }
    getTableList()
  }
  // 批量修改广告组状态
  function changeStatus(status: any) {
    if (!selectIds.value.length) {
      return Message.error('请选择广告组')
    }
    Modal.confirm({
      title: '调整状态',
      content: `请再次确认，将选中的广告组设置为${AdStatusHandle[status]}`,
      cancelText: '取消',
      okText: '确认',
      onOk: async () => {
        getSelectRows()
        requestUpdataState(selectRows.value, status, '设置成功')
      },
    })
    showUserDialog.value = true
  }
  // 拦截自动切换
  async function handleChangeIntercept() {
    return false
  }
  // 单个修改广告组状态
  function changeState(state: any, item: any) {
    let status = state === 'PAUSED' ? 'ENABLED' : 'PAUSED'
    requestUpdataState([item], status)
  }
  //修改广告组状态请求
  async function requestUpdataState(list: Array<any>, state: string, msg?: string) {
    let params = list.map((el: any) => {
      return {
        adGroupId: el.adGroupId,
        campaignId: el.campaignId,
        adType: el.adType,
        shopId: el.shopId,
        state: state,
      }
    })
    submitLoading.value = true
    const res: any = await updateAdGroup(params)
    submitLoading.value = false
    if (!res) return
    getTableList()
    if (msg) {
      Message.success(msg)
    }
  }
  // 表格内容直接编辑
  function popupChange(state: boolean, val: any) {
    if (state) {
      editVal.value = val
    }
  }
  // 修改广告组名称和竞价
  async function updateSingle(item: any, editKey: string, itemKey: string) {
    if (!editVal.value) {
      Message.error('参数必填')
      return
    }
    let params: any = {
      adGroupId: item.adGroupId,
      campaignId: item.campaignId,
      adType: item.adType,
      shopId: item.shopId,
    }
    params[editKey] = editVal.value
    if (editKey === 'bid') {
      params.adjustType = 'FIXED_AMOUNT_VALUE'
    }
    submitLoading.value = true
    let res: any = await updateAdGroup([params])
    submitLoading.value = false
    if (res) {
      // 修改组名称需要同步更新tree
      if (itemKey === 'adGroupName') {
        emit('update')
      }
      Message.success('修改成功')
      item[itemKey] = editVal.value
    }
  }
  // 打开广告详情
  function openAdGroupDetail(row: any) {
    currentData.value = row
    showAdGroupDetail.value = true
  }
  // 打开批量调整竞价
  function openEditBid() {
    if (!selectIds.value.length) {
      return Message.error('请选择广告组')
    }
    getSelectRows()
    showEditDialog.value = true
  }
  function getSelectRows() {
    selectRows.value = []
    selectIds.value.map((id) => {
      selectRows.value.push(tableListMap.value[id])
    })
  }
  defineExpose({ getTableListByVal })
</script>
<style lang="less" scoped>
  .table-gl-con {
    height: 100%;
  }
  .gray {
    color: #999;
  }
  .normal {
    color: var(--color-text-2);
  }
  .success {
    color: rgb(var(--success-5));
  }
  :deep(.arco-table-sorter) {
    margin-left: 2px;
  }
  .popconfirm-title {
    font-size: 14px;
    margin-bottom: 10px;
  }
</style>
